<?php

// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2012 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: yangweijie@topthink.net <www.thinkphp.cn>
// +----------------------------------------------------------------------

namespace Home\Controller;

use Think\Controller;
use Think\Model as MODEL;
use Think\Page;

class CommonController extends Controller {

    //初始化方法
    protected function _initialize() {
        is_login() || $this->redirect('System/login');
        /* 读取数据库中的配置 */
        $config = S('DB_CONFIG_DATA');
        if (!$config) {
            $config = api('Config/lists');
            S('DB_CONFIG_DATA', $config);
        }
        C($config); //添加配置
    }

    protected function _list($params) {
        extract($params);
        if (!isset($map))
            $map = array();
        if (!isset($parameter))
            $parameter = array();
        if (!isset($list))
            $list = array();
        if (!isset($params['source'])) {
            $this->error('错误的数据');
        } else {
            $params = array(
                'source' => $source,
                'map' => $map,
                'parameter' => $parameter,
                'listvar' => $list,
                'order' => isset($order) ? $order : '',
            );
            if (I('listRows'))
                $params['listRows'] = I('listRows');

            $this->page($params);
            if (!isset($tpl))
                $tpl = '';
            $this->display($tpl);
        }
    }

    protected function _edit() {
        $model = $_GET['model'] ? $_GET['model'] : CONTROLLER_NAME;
        $map = array(D($model)->getPk() => urldecode($_GET['id']));
        $record = D($model)->where($map)->find();
        if ($record) {
            $this->assign('record', $record);
            if (IS_AJAX) {
                exit($this->fetch());
            } else {
                $this->display();
            }
        } else {
            exit('错误的数据');
        }
    }

    //editble ajax更新方法
    public function ajaxUpdate() {
        $_POST = array(
            'id' => I('pk'),
            I('name') => I('value')
        );
        $this->update();
    }

    public function editbleAjaxGet($model, $field) {
        $list = D($model)->field($field)->select();
        exit(json_encode($list));
    }

    /**
     * 分页函数 支持数据库查询分页和数组分页 数据库分页直接传数据表名称
     * @access public
     * @param mixed  $source 分页用数据源，可以是数组或数据表
     * @param array  $map数据源为数据表的时候的查询条件
     * @param string $parameter  分页跳转的参数
     * @param string $listvar    赋给模板遍历的变量名 默认list
     * @param int    $listRows  每页显示记录数 默认20
     */
    protected function page($param) {
        extract($param);
        if (!isset($group))
            $group = array();
        import("@.ORG.Util.Page");
        $flag = !is_array($source);
        $listvar = $listvar ? $listvar : 'list';
        if (!isset($listRows))
            $listRows = 10;
        //总记录数
        if ($flag) {//字符串
            if (!isset($count))
                $count = '*';
            $totalRows = D($source)->where($map)->count($count);
        }else {
            $totalRows = ($source) ? count($source) : 1;
        }
        //创建分页对象
        $p = new Page($totalRows, $listRows, $parameter);
        //抽取数据
        if ($flag) {
            $voList = D($source)->where($map)->bind(true)->group($group)->order($order)->limit($p->firstRow . ',' . $p->listRows)->select();
            trace(D($source)->_sql(), 'sql');
        } else {
            $voList = array_slice($source, $p->firstRow, $p->listRows);
        }
        $pages = array(
            'theme' => '<div class="page">%upPage% %linkPage% %downPage%</div>',
        ); //要ajax分页配置PAGE中必须theme带%ajax%，其他字符串替换统一在配置文件中设置，
        foreach ($pages as $key => $value) {
            $p->setConfig($key, $value); // 'theme'=>'%upPage% %linkPage% %downPage% %ajax%'; 要带 %ajax%
        }
        //分页显示
        $page = $p->totalPages > 1 ? $p->show() : '';
        //模板赋值
        $this->assign($listvar, $voList);
        $this->assign("page", $page);
        $this->assign('count', $totalRows);
        $varPage = C('VAR_PAGE') ? C('VAR_PAGE') : 'p';
        $this->assign('currentPage', !empty($_GET[$varPage]) ? intval($_GET[$varPage]) : 1);
        $this->assign('listRows', $listRows);
        return $voList;
    }

    /**
     * 公共插入方法,要插入的数据模型为当前模块名，如果提价模型，则为提交的模型
     */
    public function insert() {
        $name = empty($_POST['model']) ? CONTROLLER_NAME : $_POST['model']; //添加页面提交要操作的数据模型
        $model = D($name);
        if ($data = $model->create($_POST, Model::MODEL_INSERT)) {
            //保存当前数据对象
            $list = $model->add($data);
            if ($list !== false) { //保存成功
                $jumpUrl = empty($_POST['jumpUrl']) ? $_SESSION['returnUrl'] : $_POST['jumpUrl'];
                $success = empty($_POST['success_info']) ? '新增成功' : $_POST['success_info'];
                $this->assign('jumpUrl', $jumpUrl);
                $this->success($success, $jumpUrl);
            } else {
                $error = $model->getError();
                $error = empty($error) ? '新增失败' : $model->getDbError();
                $this->error($error);
            }
        } else {
            $error = $model->getDbError() ? $model->getDbError() : $model->getError();
            $this->error($error);
        }
    }

    /**
     * 切换状态
     */
    public function status($info) {
        $_POST = $_GET;
        C('update_status', true);
        $this->update($info);
        $this->after_status($_POST['model'], $_POST['status']);
    }

    public function resume($model, $post, $msg) {
        $_GET['model'] = $model;
        $_GET['status'] = 1;
        $post = parse_url('http://baidu.com' . $post);
        if ($post)
            $_GET = array_merge($post, $_GET);
        $this->status(array_values($msg));
    }

    public function forbid($model, $post, $msg = '') {
        $_GET['model'] = $model;
        $_GET['status'] = 0;
        $post = parse_url('http://baidu.com' . $post);
        if ($post)
            $_GET = array_merge($post, $_GET);
        $this->status(array_values($msg));
    }

    /**
     * 公共更新数据模型 默认模型名称为当前模块名，如果提交模型名，则为post接收的模型
     */
    public function update($info = array('更新成功', '更新失败')) {
        $name = empty($_POST['model']) ? CONTROLLER_NAME : $_POST['model'];
        // d_f('out',$name);
        $model = D($name);
        if ($data = $model->create($_POST)) {
            $o_data = $model->find($data[$model->getPk()]);
            d_f('debug', $data);
            $result = $model->save($data);
            d_f('debug', $model->_sql());
            //更新之后操作
            if (false !== $result) {
                //成功提示
                $jumpUrl = empty($_POST['jumpUrl']) ? $_SESSION['returnUrl'] : $_POST['jumpUrl'];
                $this->success($info[0], $jumpUrl);
            } else {
                //错误提示
                $error = $model->getDbError();
                $error = empty($error) ? $info[1] : $error;
                $this->error($error);
            }
        } else {
            $error = $model->getDbError();
            $this->error($error);
        }
    }

    /**
     * 公共删除一入口
     * 接受参数value类型为 模型-id值,其中多个id值用,隔开
     */
    public function delete() {
        $name = empty($_POST['model']) ? CONTROLLER_NAME : $_POST['model'];
        $id = I('id');
        $model = D($name); //定义模型
        $pk = $model->getPk();
        $map[$pk] = array("IN", $id);
        $data['title'] = "Id：" . $value[1];
        $data['model'] = $name;
        //判断删除之前是否存在检查删除操作
        if (method_exists($this, '_check_delete'))
            $this->_check_delete($id, $name);
        //删除操作
        $model->startTrans();
        if ('recycle' == $action) {
            $result = $model->where($map)->setField('status', -1);
            $info = '放入回收站中';
        } elseif ('restore' == $action) {
            $result = $model->where($map)->setField('status', 1);
            $info = '还原成功';
        } else {
            $data = $model->where($map)->find();

            $result = $model->where($map)->delete();
            //删除之后操作
            $result = $result && $this->after_delete($id, $name, $data);
            $info = '删除成功';
        }
        if ($result) {
            $model->commit();
            $this->success($info);
        } else {
            $model->rollback();
            $this->error('删除失败');
        }
    }

    //清空数据
    public function deleteAll() {
        $model = $_GET['model'];
        if (empty($model)) {
            $this->error('操作模型未知');
        } else {
            $map['id'] = array('neq', 0);
            $result = M($model)->where($map)->delete();
            if ($result) {
                $this->success('删除成功');
            } else {
                $this->error('删除失败');
            }
        }
    }

    //排序传值
    public function sort() {
        $array = split("-", $_GET["value"]);
        $id = split(",", $array[1]);
        if (count($id) > 1) {
            $map['id'] = array("in", $id);
            $order = 'sort asc,id asc';
        } else {
            $limit = 20;
            $order = 'id asc';
        }
        $model = D($array[0]);
        $list = $model->where($map)->order($order)->limit($limit)->select();
        $this->model = $array[0];
        $this->id = $array[1];
        $this->assign("list", $list);
        $this->display();
    }

    //数据库排序的update
    public function updateSort() {
        $model = D($_POST['model']);
        $id = explode(',', $_POST['id']);
        if ($_POST['clear'] == '清空排序') {
            $map['id'] = array('in', $id);
            $model->where($map)->setField('sort', null);
            $this->success('排序已清空!');
        } else {
            foreach ($id as $key => $vo) {
                $map['id'] = $vo;
                $data['sort'] = $key + 1;
                $model->where($map)->save($data);
            }
            $this->success('排序成功!');
        }
    }

    public function ajaxUpload($params = array('model'=>'File','field'=>'file')) {
        $result = $this->upload($params);
        if ($result['status']) {
            $file = $result['files'][0];
            unset($result['status']);
            $this->success('上传成功', '', $result);
        } else {
            $this->error('上传失败：' . $result['info']);
        }
    }

    protected function upload($params) {
        /* 返回标准数据 */
        $return = array('status' => 1, 'info' => '上传成功', 'data' => '');
        $model = $params['model'] == 'Picture'? 'Picture' : 'File';
        /* 调用文件上传组件上传文件 */
        $table = D($model);
        $driver = C("{$model}_UPLOAD_DRIVER");
        d_f('upload', $driver);
        $upload_config = C("{$model}_UPLOAD");
        d_f('upload', $upload_config);
        if(isset($params['rootPath']))
            $upload_config['rootPath'] = $params['rootPath'];
        $info = $table->upload($_FILES, $upload_config, $driver, C("UPLOAD_{$driver}_CONFIG"));
        d_f('upload', $info);
        /* 记录图片信息 */
        if ($info) {
            $return['status'] = 1;
            $return = array_merge($info[$params['field']], $return);
            if (method_exists($this, 'after_upload')) {
                $this->after_upload(CONTROLLER_NAME, $info, $result);
            }
        } else {
            $return['status'] = 0;
            $return['info'] = $table->getError();
        }

        return $return;
    }

    protected function after_delete($id, $name, $data = '') {
        return true;
    }

    public function after_status($name, $flag) {
        return true;
    }

}
